<template>
  <div class="add-sales-box" @click="promoteIndex">
    <swh-drag-box
      :title="'新增销售清单'"
      :zIndex="99"
      :top="'70px'"
      :isMask="false"
      :isPadding="false"
      @closePortability="close"
      @confirmDarg="confirmBox"
    >
      <div class="sales-list">
        <div class="customer">
          <div class="customer-input">
            <span>客户：</span>
            <el-select
              v-model="activeCustomId"
              filterable
              placeholder="输入客户名称"
              style="width: 240px"
              @change="changeCustom"
            >
              <el-option
                v-for="item in customOptions"
                :key="item.id"
                :label="item.customerName"
                :value="item.id"
              >
                <span style="padding-left: 20px">{{ item.customerName }}</span>
              </el-option>
            </el-select>
          </div>
          <p class="tips" v-if="customerArrears">
            客户欠款：{{ customerArrears }} 元
          </p>
          <div class="date-input">
            <span>{{ week }}</span>
            <el-date-picker
              v-model="salesDate"
              type="datetime"
              placeholder="选择日期"
              @change="changeDate"
              :style="{ width: '180px' }"
              :clearable="false"
            >
            </el-date-picker>
          </div>
        </div>
        <div class="customer-sales">
          <div class="sales-title">
            <p
              class="sales-title-item"
              v-for="item in salesListConfig"
              :key="item.code"
              :style="{ flex: item.share, width: item.width }"
              @dblclick="lookBuyingPrice(item.code)"
            >
              {{ item.name }}
            </p>
          </div>
          <div class="customer-sales-box">
            <div
              class="customer-sales-item"
              v-for="(item, index) in salesList"
              :key="item.id"
            >
              <div
                class="sales-item-name"
                v-for="i in salesListConfig"
                :key="i.code"
                :style="{ flex: i.share, width: i.width }"
              >
                <span v-if="i.code === 'index'">{{ index + 1 }}</span>

                <el-select
                  v-if="i.code === 'commodityNameId'"
                  v-model="item[i.code]"
                  filterable
                  :filter-method="(value) => (keyword = value)"
                  placeholder="名称及型号"
                  @change="(val) => changeCommodity(val, item)"
                >
                  <el-option
                    v-for="item in customFilter()"
                    :key="item.commodityId"
                    :label="item.commodityName"
                    :value="item.commodityId"
                  >
                    <span style="padding-left: 20px">{{
                      item.commodityName
                    }}</span>
                  </el-option>
                </el-select>
                <el-input
                  v-if="i.code === 'num'"
                  type="number"
                  :min="0"
                  v-model="item[i.code]"
                  placeholder="数量"
                  :disabled="!item['commodityNameId']"
                  @input="(val) => changeValue(val, item, 'num')"
                ></el-input>
                <el-tooltip
                  v-if="i.code === 'price'"
                  effect="dark"
                  :content="`进价：${item['buyingPrice']}`"
                  placement="right"
                  :disabled="!item['commodityNameId'] || !isShowBuyingPrice"
                >
                  <el-input
                    v-model="item[i.code]"
                    :disabled="!item['commodityNameId']"
                    placeholder="单价"
                    @input="(val) => changeValue(val, item, 'price')"
                  ></el-input>
                </el-tooltip>

                <span v-if="i.code === 'amount'" class="inventory">{{
                  item[i.code]
                }}</span>
                <el-input
                  v-if="i.code === 'remark'"
                  v-model="item[i.code]"
                  :disabled="!item['commodityNameId']"
                  placeholder="备注"
                ></el-input>
                <span
                  v-if="i.code === 'inventory'"
                  @click="addPurchaseList(item)"
                  class="inventory"
                  :class="{ red: item[i.code] <= item['reminderCount'] }"
                  >{{ item[i.code] }}</span
                >
                <div v-if="i.code === 'operation'" class="operation">
                  <span
                    class="del"
                    v-if="salesList.length > 1"
                    @click="delSales(index)"
                    >删除</span
                  >
                  <span
                    class="add"
                    v-if="salesList.length - 1 == index"
                    @click="addSales"
                    >添加</span
                  >
                </div>
              </div>
            </div>
          </div>
        </div>
        <!-- 底部 -->
        <div class="total-box">
          <div class="status">
            <el-radio
              v-model="billingStatus"
              label="1"
              :style="{ color: 'red' }"
              >记账</el-radio
            >
            <el-radio
              v-model="billingStatus"
              label="0"
              :style="{ color: 'green' }"
              >结清</el-radio
            >
          </div>
          <div class="total-amount">
            <span class="red-text total-profit">总成本：{{ totalCost }}</span>
            <span class="red-text total-profit">总利润：{{ totalProfit }}</span>
            <span>应收总额：</span>
            <span class="red-text">{{ totalAmount }}</span>
            <span class="icon-dengyu" @click="actualAmount = totalAmount">
              =>
            </span>
            <span>实际收款：</span>
            <el-input
              :style="{ width: '120px', marginTop: '4px' }"
              v-model="actualAmount"
              placeholder="实际收款"
              @change="actualAmountChangeFn"
            ></el-input>
          </div>
        </div>
      </div>
    </swh-drag-box>
  </div>
</template>

<script>
import { reactive, toRefs, onBeforeMount, onMounted } from 'vue';
import { salesListConfig } from './task.js';
import { setLS, getLS, formatDateString, amend } from '@/utils/common.js';
export default {
  name: '',
  setup(props, ctx) {
    const data = reactive({
      saleDataLS: {},
      isShowBuyingPrice: false,
      salesListConfig,
      customOptions: [],
      commodityList: [],
      activeCustomId: '',
      customerName: '',
      customerArrears: '', //欠款
      salesDate: new Date(),
      week: '',
      keyword: '', //苦拼筛选
      salesList: [
        //名称，单位，数量，单价，金额，备注
        {
          id: Date.now().toString(16),
          commodityNameId: '',
          commodityName: '',
          num: '',
          price: '',
          amount: '',
          remark: '',
          inventory: '',
          buyingPrice: '',
          profit: '' //利润
        }
      ],
      totalAmount: 0, //应收总额
      totalProfit: 0, //利润总额
      totalCost: 0, //成本总额
      actualAmount: 0, //实际收款总额
      billingStatus: '',
      commodityData: [],
      actualAmountChangeNum: 0,
      LSData: {}
    });
    onBeforeMount(() => {});
    onMounted(() => {
      init();
    });
    const init = () => {
      data.saleDataLS = getLS('SALE_LIST') || {};
      data.week = formatDateString(data.salesDate, 'week');
      // 获取客户名单
      data.LSData = getLS('PURCHASE_AND_CUSTOMER') || {};
      if (data.LSData && data.LSData.customer.length > 0) {
        data.customOptions = data.LSData.customer;
      }
      // 获取商品名单
      data.commodityData = getLS('COMMODITY_DATA');
      if (data.commodityData && data.commodityData.length > 0) {
        data.commodityData.forEach((item) => {
          data.commodityList.push(...item.commodityLists);
        });
      }
    };
    // 自定义筛选,返回符合条件的下拉数组
    const customFilter = () => {
      if (data.keyword === '') {
        return data.commodityList;
      } else {
        return data.commodityList.filter((item) => {
          return (
            String(item.commodityName)
              .toUpperCase()
              .includes(data.keyword.toUpperCase()) ||
            String(item.commodityQueryCode)
              .toUpperCase()
              .includes(data.keyword.toUpperCase())
          );
        });
      }
    };
    // 添加至进货列表
    const addPurchaseList = (val) => {
      console.log('加入进货清单', val);
    };
    // 选择后获取客户名称保存至订单信息中
    const changeCustom = (val, item) => {
      const targetObj = data.customOptions.filter((i) => i.id === val)[0];
      data.customerName = targetObj.customerName;
      data.customerArrears = targetObj.arrears;
    };
    // 日期改变
    const changeDate = () => {
      if (!data.salesDate) {
        data.salesDate = new Date();
      }
      data.week = formatDateString(data.salesDate, 'week');
    };
    // 删除单个销售条目，从新计算总额
    const delSales = (index) => {
      data.salesList.splice(index, 1);
      changeTotalAmount();
    };
    // 添加清单条目
    const addSales = () => {
      data.salesList.push(
        //名称，单位，数量，单价，金额，备注
        {
          id: Date.now().toString(16),
          commodityNameId: '', //名称
          commodityName: '',
          num: '', //数量
          price: '', //单价
          amount: '', //金额
          remark: '', //备注
          inventory: '', //库存
          buyingPrice: '', //进货价
          profit: '' //利润
        }
      );
    };
    // 选择商品后，自动回显，单价和库存
    const changeCommodity = (val, item) => {
      const targetObj = data.commodityList.filter(
        (i) => i.commodityId === val
      )[0];
      item.price = targetObj.retailPrice;
      item.inventory = targetObj.inventoryNumber;
      item.reminderCount = targetObj.reminderCount;
      item.buyingPrice = targetObj.buyingPrice;
      item.commodityName = targetObj.commodityName;
      // 如果选择数量，自动计算总额
      if (item.num) {
        changeValue(item.num, item, 'num');
      }
    };
    // 数量变化，计算单个总数，计算总计
    const changeValue = (val, item, type) => {
      if (item.commodityNameId) {
        if (type == 'num') {
          item.amount = val * item.price;
          item.buying = val * item.buyingPrice;
          item.profit = val * (item.price - item.buyingPrice);
        } else if (type == 'price') {
          item.amount = val * item.num;
          item.profit = item.num * (val - item.buyingPrice);
        }
      }
      // 计算全部总数量
      changeTotalAmount();
    };
    // 实际收款改变
    const actualAmountChangeFn = (val) => {
      // 计算新的利润  实际收款金额 - 应收总额 是多出来利润
      data.actualAmountChangeNum = val - data.totalAmount;
      console.log(data.actualAmountChangeNum);
    };
    // 计算全部总额
    const changeTotalAmount = () => {
      data.totalAmount = 0;
      data.actualAmount = 0;
      data.totalProfit = 0;
      data.totalCost = 0;
      data.salesList.forEach((i) => {
        if (i.amount) {
          data.totalProfit = amend(data.totalProfit, i.profit, '+');
          data.totalAmount = amend(data.totalAmount, i.amount, '+');
          data.totalCost = amend(data.totalCost, i.buying, '+');
          data.actualAmount = data.totalAmount;
        }
      });
    };
    const close = () => {
      ctx.emit('addSalesClose');
    };
    // 确认添加
    const confirmBox = () => {
      const {
        salesList,
        activeCustomId,
        customerName,
        salesDate,
        actualAmount,
        totalAmount,
        totalProfit,
        totalCost,
        billingStatus,
        actualAmountChangeNum,
        week
      } = data;
      // 客户验证
      if (!activeCustomId) {
        Message({
          type: 'error',
          content: '请选择客户'
        });
        return;
      }

      //判断salesList中是否都有num值
      let isAllNum = true;
      salesList.forEach((item) => {
        if (item.num < 1) {
          isAllNum = false;
        }
      });
      if (!isAllNum) {
        Message({
          type: 'error',
          content: '请填写物品数量'
        });
        return;
      }
      // 订单状态验证
      if (!billingStatus) {
        Message({
          type: 'error',
          content: '请选择订单状态'
        });
        return;
      }
      ConfirmBox({
        title: '提示',
        content: `确认保存销售清单？`
      })
        .then(() => {
          init();
          // 整理销售保存的信息
          const salesData = {
            id: `sale_${Date.now().toString(16)}`,
            salesList, //销售物品清单
            customerId: activeCustomId, //客户id
            customerName,
            week, //星期
            salesDate, //日期
            salesDateStr: formatDateString(data.salesDate, 'YYYY-MM-DD'),
            salesTimeStr: formatDateString(data.salesDate, 'HH-MM-SS'),
            actualAmount, //实际收款
            totalAmount, //应收总额
            totalProfit, //利润总额
            totalCost, //成本总额
            billingStatus, //订单状态   0结清   1记账
            actualAmountChangeNum,
            billingStatusText: billingStatus == '0' ? '结清' : '记账' //订单状态文字
          };
          // 按日期保存销售数据
          if (
            data.saleDataLS[salesData.salesDateStr] &&
            data.saleDataLS[salesData.salesDateStr].length > 0
          ) {
            data.saleDataLS[salesData.salesDateStr].unshift(salesData);
          } else {
            data.saleDataLS[salesData.salesDateStr] = [salesData];
          }
          // 更新库存数量
          recalculateInventory();
          updateCustomerInfo(activeCustomId, actualAmount, billingStatus);
          setLS('PURCHASE_AND_CUSTOMER', data.LSData);
          setLS('COMMODITY_DATA', data.commodityData);
          setLS('SALE_LIST', data.saleDataLS);
          ctx.emit('addSalesConfirmBox');
        })
        .catch(() => {});
    };
    //从新计算库存（减少）
    const recalculateInventory = () => {
      data.salesList.forEach((item) => {
        // 遍历商品分类
        data.commodityData.forEach((classObj) => {
          // 遍历分类下的商品commodity
          classObj.commodityLists.forEach((commodity) => {
            if (item.commodityNameId == commodity.commodityId) {
              commodity.inventoryNumber = commodity.inventoryNumber - item.num;
            }
          });
        });
      });
    };
    // 更新客户信息，增加订单更新，累计金额，欠款金额
    const updateCustomerInfo = (
      activeCustomId,
      actualAmount,
      billingStatus
    ) => {
      data.customOptions.forEach((item) => {
        if (item.id == activeCustomId) {
          item.transactionNum += 1;
          item.totalAmount += Number(actualAmount || 0); //累计金额
          if (billingStatus == '1') {
            item.arrears += Number(actualAmount || 0); //欠款金额
          }
        }
      });
    };
    // 点击提升弹窗层级
    const promoteIndex = () => {
      ctx.emit('promoteIndex');
    };
    //双击可查看进价
    const lookBuyingPrice = (code) => {
      if (code === 'price') {
        data.isShowBuyingPrice = !data.isShowBuyingPrice;
      }
    };
    return {
      customFilter,
      addPurchaseList,
      actualAmountChangeFn,
      changeCustom,
      lookBuyingPrice,
      delSales,
      changeValue,
      changeCommodity,
      addSales,
      changeDate,
      promoteIndex,
      confirmBox,
      close,
      ...toRefs(data)
    };
  }
};
</script>
<style lang="less">
.customer {
  .el-input__wrapper {
    border: none !important; /* 取消边框 */
    box-shadow: none !important; /* 取消阴影 */
  }
}
.sales-item-name {
  .el-select__wrapper {
    border: none !important; /* 取消边框 */
    box-shadow: none !important; /* 取消阴影 */
  }

  .el-input__wrapper {
    border: none !important; /* 取消边框 */
    box-shadow: none !important; /* 取消阴影 */
  }
}
.total-amount {
  .el-input__inner {
    color: red;
    font-weight: 700;
    font-size: 16px;
  }
}
</style>

<style scoped lang="less">
.add-sales-box {
  .sales-list {
    width: 900px;
    border-radius: 5px;
    position: relative;
    padding-top: 40px;
    box-sizing: border-box;
    padding-bottom: 40px;
    margin-bottom: 10px;
    .customer {
      position: absolute;
      width: 100%;
      height: 40px;
      line-height: 40px;
      top: 0px;
      padding: 0px 20px;
      box-sizing: border-box;
      .customer-input {
        float: left;
        display: flex;
        align-items: center;
        span {
          font-size: 14px;
          color: @HSB;
        }
      }
      .tips {
        float: left;
        font-size: 14px;
        color: red;
        margin-left: 30px;
      }
      .date-input {
        float: right;
        display: flex;
        align-items: center;
        span {
          font-size: 14px;
          color: @HSB;
        }
      }
    }
    .customer-sales {
      position: relative;
      padding-top: 30px;
      box-sizing: border-box;
      width: 100%;

      .sales-title {
        position: absolute;
        top: 0;
        width: 100%;
        display: flex;
        background: @HSE;
        line-height: 30px;
        .sales-title-item {
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          text-align: center;
          font-size: 14px;
        }
      }
      .customer-sales-box {
        height: 100%;
        min-height: 300px;
        max-height: 500px;
        overflow: auto;
        .customer-sales-item {
          line-height: 30px;
          display: flex;
          .sales-item-name {
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            text-align: center;
            font-size: 14px;
            border: 1px solid @HSE;
            border-top: none;
            .operation {
              display: flex;
              align-items: center;
              justify-content: center;
              height: 30px;
              line-height: 30px;
              span {
                flex: 1;
                cursor: pointer;
                text-align: center;
                margin-top: 3px;
                &.del {
                  color: red;
                }
                &.add {
                  color: green;
                }
                &:hover {
                  opacity: 0.8;
                }
              }
            }
            .inventory {
              display: block;
              margin-top: 2px;
              font-size: 14px;
              color: @HSC;
              cursor: pointer;

              &.red {
                background: red;
                color: #fff;
              }
            }
          }
          &:hover {
            background: @TSD;
          }
        }
      }
    }
    .total-box {
      position: absolute;
      width: 100%;
      height: 40px;
      bottom: 0px;
      padding: 0px 20px;
      box-sizing: border-box;
      border-top: 1px solid #ddd;
      .status {
        float: left;
        line-height: 40px;
      }
      .total-amount {
        float: right;
        font-size: 14px;
        color: @HSB;
        .icon-dengyu {
          margin: 0 10px;
          cursor: pointer;
          &:hover {
            color: @TSB;
          }
        }
        span {
          float: left;
          line-height: 40px;
          &.red-text {
            min-width: 50px;
            font-weight: 700;
            color: red;
          }
          &.total-profit {
            margin-right: 50px;
            cursor: pointer;
            opacity: 0;
            transition: 0.3s;
            &:hover {
              opacity: 0.8;
            }
          }
        }
      }
    }
  }
}
</style>
